import smbus2
import time

GW_GRAY_ADDR = 0x4C
bus = smbus2.SMBus(1)  # 树莓派默认使用I2C总线1

def ping_sensor():
    timeout = time.time() + 5  # 5秒超时
    while True:
        try:
            # 发送握手命令0xAA
            bus.write_byte(GW_GRAY_ADDR, 0xAA)
            # 读取1字节状态
            status = bus.read_byte(GW_GRAY_ADDR)
            if status == 0x66:
                return True
        except IOError:
            pass
        
        if time.time() > timeout:
            print("Ping timeout!")
            return False
        time.sleep(0.01)

def setup():
    if not ping_sensor():
        exit(1)
    # 发送启动测量命令0xD0
    bus.write_byte(GW_GRAY_ADDR, 0xD0)
    print("Sensor initialized")

def read_rgb():
    data = bus.read_i2c_block_data(GW_GRAY_ADDR, 0, 24)
    return data[0], data[1], data[2]

if __name__ == "__main__":
    setup()
    try:
        while True:
            r, g, b = read_rgb()
            print(f"R:{r} G:{g} B:{b}")
            time.sleep(0.5)
    except KeyboardInterrupt:
        bus.close()